package com.doform.android.xianggucheng.retrofit;

import com.doform.android.xianggucheng.bean.ApiBean;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 作者 Y_MS
 * Created by ${APEN} on 2017-08-01.
 * GitHub：https://github.com/cxydxpx
 */

class ApiSpecBeanJsonDeserializer implements JsonDeserializer<ApiBean> {
    @Override
    public ApiBean deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        JsonObject jsonObject = json.getAsJsonObject();
        boolean rs = jsonObject.get("rs").getAsBoolean();
        ApiBean apiBean = new ApiBean();
        apiBean.setRs(rs);

        if (rs) {//访问服务器成功
           /*获取ApiBean.data的类型*/
            Type realType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];

                JsonElement rawDataJsonElement = jsonObject.get("data");
                apiBean.setData(
                        context.deserialize(rawDataJsonElement, realType)
                );
        } else {//访问服务器失败
            JsonElement dataElement = jsonObject.get("data");
            String errorStr;
                if (dataElement == null) {
                    errorStr = "服务器开小差了...";
                } else if (dataElement.isJsonPrimitive()) {
                    errorStr = dataElement.getAsString();
            } else {
                errorStr = dataElement.toString();
            }

            apiBean.setErrorMessage(errorStr); //
        }

        return apiBean;
    }
}
